package com.kkb.controller;
import com.kkb.pojo.Menu;
import com.kkb.pojo.User;
import com.kkb.service.RoleService;
import com.kkb.service.UserService;
import com.kkb.vo.ResultVo;
import com.kkb.vo.UserQueryVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Lxy
 * @create 2022-03-18 15:52
 */

@Controller
public class LoginController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    //处理用户登录验证
    @ResponseBody
    @RequestMapping(value = "login",method = RequestMethod.GET)
    public ResultVo<User> LoginCheck(UserQueryVo vo, HttpServletRequest request){
        if(vo != null){
            List<User> userList = userService.getUser(vo);
            if (userList != null && userList.size() != 0){
                User user = userList.get(0);
                request.getSession().setAttribute("user",user);
                return new ResultVo<User>(user);
            }
        }
        return new ResultVo<>(400,"用户请求错误");
    }

    //登录页跳转首页通过用户权限把对应菜单加载
    @RequestMapping(value = "index",method = RequestMethod.GET)
    public ModelAndView jumpIndex(HttpServletRequest request){
        HttpSession session = request.getSession();
        ModelAndView mv = new ModelAndView();
        User user = (User) session.getAttribute("user");
        Integer r_id = user.getR_id();
        List<Menu> menuList = roleService.getMenuListByRid(r_id);
        session.setAttribute("menuList",menuList);
        mv.setViewName("redirect:/welcome/index.jsp");
        return mv;
    }

    @RequestMapping(value = "logout",method=RequestMethod.GET)
    public ModelAndView logout(HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        request.getSession().invalidate();
        mv.setViewName("redirect:/welcome/login.html");
        return mv;
    }


}
